package cn.sh.yhk.acl;

import cn.sh.yhk.acl.cache.UserTokenCacheService;
import cn.sh.yhk.acl.jwt.JwtTokenUtil;
import cn.sh.yhk.base.vo.BaseResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname Yhk
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/10/7 15:44
 * @Created by y6522
 */
@Component
@Slf4j
public class UserLogoutHandler implements LogoutHandler {
    @Autowired
    private UserTokenCacheService tokenCacheService;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        try {
            String token = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
            String userName = JwtTokenUtil.getUserNameFromToken(token);
            tokenCacheService.userTokenCacheDelete(userName);
            BaseResponse map = BaseResponse.success("logout成功");
            response.setCharacterEncoding("utf-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            ObjectMapper objectMapper = new ObjectMapper();
            String resBody = objectMapper.writeValueAsString(map);
            PrintWriter printWriter = null;
            printWriter = response.getWriter();
            printWriter.print(resBody);
            printWriter.flush();
            printWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
